<?php


namespace App\Models;


class Carts extends Base
{
    protected $fillable = [
        'id','user_id','store_id','store_name','goods_id','goods_name','goods_img','goods_price','num','created_at','updated_at'
    ];

    /**
     * 所有数据
     * @param array $params 条件参数
     * @param array $fields 查询的字段
     * @param int $limit 分页数量
     * @return mixed
     */
    protected function allLists($params = [], $fields = ['*'], $page = '', $limit = 10){
        $params['status'] = 1;
        if(isset($page)){
            $lists = $this->select($fields)
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                })->orderBy('created_at', 'desc')->paginate($limit, null, null, $page);
        }else{
            $lists = $this->select($fields)
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                })->orderBy('created_at', 'desc')->get();
        }

        return $lists;
    }


    /**
     * 购物车列表
     * @access public
     * @author csdeshang
     * @param string $type 存储类型 db,cookie
     * @param array $condition 检索条件
     * @param int $limit 限制
     * @return array
     */
    protected function getCartList($params = [], $fields = ['*'], $limit = '') {
        $cart_list = $this->select($fields)
            ->where(function ($query) use ($params) {
                if(isset($params['cart_id']) && $params['cart_id']) {
                    $query ->whereIn('id',$params['cart_id']);
                }
                if(isset($params['user_id']) && $params['user_id']) {
                    $query ->where('user_id',$params['user_id']);
                }
                if(isset($params['status']) && $params['status']) {
                    $query ->where('status',$params['status']);
                }
            })->get();

        //顺便设置购物车商品数和总金额
        $cart_list->cart_goods_num = count($cart_list);
        $cart_all_price = 0;
        if(!empty($cart_list)){
            foreach ($cart_list as $val) {
                $goods_freight = Goods::where('id',$val['goods_id'])->value('freight');
                $cart_all_price += $val['goods_price'] * $val['num'] + $goods_freight;
            }
        }
        $cart_list->cart_all_price = Buys::ds_price_format($cart_all_price);
        return $cart_list;
    }

}